package main;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import model.Book;
import model.Chapter;
import model.Page;

public class Main {

	String[] list = new String[] {//"http://truyen.vnsharing.net/Truyen/Sexual-Hunter-Riot",
			"http://truyen.vnsharing.net/Truyen/Cau-truyen-cua-Minamoto",
//			"http://truyen.vnsharing.net/Truyen/Minimum-17-",
//			"http://truyen.vnsharing.net/Truyen/Gantz----",
//			"http://truyen.vnsharing.net/Truyen/Futari-no-Maharaja",
//			"http://truyen.vnsharing.net/Truyen/Delivery-Cinderella00",
//			"http://truyen.vnsharing.net/Truyen/Communication-is-still-an-issue",
//			"http://truyen.vnsharing.net/Truyen/Bra-Girl",
//			"http://truyen.vnsharing.net/Truyen/Kamisama-no-Iutoori-II",
//			"http://truyen.vnsharing.net/Truyen/Kiss-X-Sis",
//			"http://truyen.vnsharing.net/Truyen/Kono-S-o-Mi-yo-BT",
//			"http://truyen.vnsharing.net/Truyen/Mousou-Cherry",
//			"http://truyen.vnsharing.net/Truyen/Kamisama-no-Iutoori-II",
//			"http://truyen.vnsharing.net/Truyen/Kono-S-o-Mi-yo-BT0," +
//			"http://truyen.vnsharing.net/Truyen/Mama-wa-Doukyuusei7",
//			"http://truyen.vnsharing.net/Truyen/Megu-Miruku",
//			"http://truyen.vnsharing.net/Truyen/Mujaki-no-Rakuen----",
//			"http://truyen.vnsharing.net/Truyen/Nekoka-Kareshi-no-Ayashikata",
//			"http://truyen.vnsharing.net/Truyen/Ren-ai-Shijou-Shugi",
//			"http://truyen.vnsharing.net/Truyen/Saezuru-Tori-wa-Habatakanai",
//			"http://truyen.vnsharing.net/Truyen/Saikin-Imouto-no-Yousuga-Chotto-Okashii-n-da-ga",
//			"http://truyen.vnsharing.net/Truyen/My-Feeling-Rivetra-SnK-Dou",
//			"http://truyen.vnsharing.net/Truyen/Silence",
//			"http://truyen.vnsharing.net/Truyen/SS-Sisters",
//			"http://truyen.vnsharing.net/Truyen/Sun-Ken-Rock--",
//			"http://truyen.vnsharing.net/Truyen/USOTSUKI-PARADOX",
//			"http://truyen.vnsharing.net/Truyen/Wolf-Guy-Wolfen-Crest",
//			"http://truyen.vnsharing.net/Truyen/Yomeiro-Choice-1",
			/*"http://truyen.vnsharing.net/Truyen/Yuureitou"*/};
	final String BASE_DIR = "D:/Comics";
	public static void main(String... args) throws IOException, URISyntaxException {
		Main __main = new Main();
//		__main.startDownload();
		__main.prepareBooks();
	}
	
	public void prepareBooks() throws IOException {
		for (String bookUrl : list) {
			URL myUrl = new URL(bookUrl);
			URL confirmedUrl = new URL(bookUrl + "?confirm=yes");
			String file = myUrl.getFile();
			String bookName = file.substring(file.lastIndexOf("/") + 1);
			final String baseUrl = bookUrl.substring(0, bookUrl.indexOf(file));
			String line;
			String coverUrl = null;
			List<String> chapters = new ArrayList<String>();

			BufferedReader in = new BufferedReader(new InputStreamReader(
					confirmedUrl.openStream()));
			while ((line = in.readLine()) != null) {
				if (line.contains("<a  href=\"" + file)) {
					chapters.add(line.substring(line.indexOf("\"") + 1, line.lastIndexOf("\"")));
				} else if (line.contains("<link rel=\"image_src\" href=")) {
					String tmp = line.substring(line.indexOf("href"));
					coverUrl = tmp.substring(tmp.indexOf("\"") + 1, tmp.lastIndexOf("\""));
				}
			}
			in.close();
			
			Book book = new Book();
			book.setName(bookName);
			book.setCover(coverUrl);
			
			for (int i = 0; i < chapters.size(); i++) {
				Chapter chapter = getChapter(baseUrl + chapters.get(i));
				chapter.setName(chapters.get(i));
				chapter.setChapterOrder(i);
				book.getChapters().add(chapter);
			}
			
			book.debug();
		}
	}
	
	public Chapter getChapter(String chapterUrl) throws IOException {
		Chapter chapter = new Chapter();
		
		URL myUrl = new URL(chapterUrl);
	    BufferedReader in = new BufferedReader(
	                        new InputStreamReader(
	                        myUrl.openStream()));

	    String line;
	    List<String> picUrlList = new ArrayList<String>();

	    while ((line = in.readLine()) != null) {
	    	if (line.contains("lstImages.push(") && line.contains("imgmax=2000")) {
	    		String picUrl = line.substring(line.indexOf("lstImages.push(") + "lstImages.push(".length() + 1, line.indexOf("imgmax=2000") + "imgmax=2000".length());
	    		picUrlList.add(picUrl);
	    	}
	    }
	    in.close();
	    
	    for (int i = 0; i < picUrlList.size(); i++) {
	    	Page page = new Page();
	    	page.setLink(picUrlList.get(i));
	    	page.setPageOrder(i);
	    	chapter.getPages().add(page);
		}
		
		return chapter;
	}
	
	
	private void startDownload() throws IOException, URISyntaxException {
		for (String bookUrl : list) {
			URL myUrl = new URL(bookUrl);
			URL confirmedUrl = new URL(bookUrl + "?confirm=yes");
			String file = myUrl.getFile();
			String bookName = file.substring(file.lastIndexOf("/") + 1);
			final String baseUrl = bookUrl.substring(0, bookUrl.indexOf(file));
			final File bookDir = new File (BASE_DIR + "/" + bookName);
			bookDir.mkdir();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					confirmedUrl.openStream()));

			String line;
			String coverUrl = null;
			List<String> chapters = new ArrayList<String>();
			while ((line = in.readLine()) != null) {
				if (line.contains("<a  href=\"" + file)) {
					chapters.add(line.substring(line.indexOf("\"") + 1, line.lastIndexOf("\"")));
				} else if (line.contains("<link rel=\"image_src\" href=")) {
					String tmp = line.substring(line.indexOf("href"));
					coverUrl = tmp.substring(tmp.indexOf("\"") + 1, tmp.lastIndexOf("\""));
				}
			}
			in.close();
			if (coverUrl != null) {
				saveImage(coverUrl, bookDir, "cover.jpg");
			}
			if (chapters.size() == 0) {
				System.err.println("Failed: " + bookUrl);
			}
			for (final String chapter : chapters) {
				dowloadChapter(baseUrl + chapter, chapter.substring(chapter.lastIndexOf("/") + 1, chapter.lastIndexOf("?")), bookDir);
			}
		}
	}

	public void dowloadChapter(final String chapterUrl, final String chapterName, final File downloadDir) throws IOException, URISyntaxException {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					File chapterDir = new File(downloadDir, chapterName);
					chapterDir.mkdir();
					URL myUrl = new URL(chapterUrl);
				    BufferedReader in = new BufferedReader(
				                        new InputStreamReader(
				                        myUrl.openStream()));
	
				    String line;
				    List<String> picUrlList = new ArrayList<String>();
	
				    while ((line = in.readLine()) != null) {
				    	if (line.contains("lstImages.push(") && line.contains("imgmax=2000")) {
				    		String picUrl = line.substring(line.indexOf("lstImages.push(") + "lstImages.push(".length() + 1, line.indexOf("imgmax=2000") + "imgmax=2000".length());
				    		picUrlList.add(picUrl);
				    	}
				    }
				    in.close();
				    for (String picUrl : picUrlList) {
				    	saveImage(picUrl, chapterDir, null);
					}
	
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}).start();
		
	}
	
	public void saveImage(String pageUri, File chapterDir, String specificName) throws URISyntaxException, MalformedURLException, IOException {
		try {
			URI uri = new URI(pageUri);
			String query = uri.getPath();
			String fileName = specificName == null ? query.substring(query.lastIndexOf("/") + 1) : specificName;
			fileName = URLDecoder.decode(fileName, "UTF-8");
			InputStream is = uri.toURL().openStream();
			OutputStream os = new FileOutputStream(chapterDir.getAbsolutePath() + "/" + fileName);
	
			byte[] b = new byte[1024000];
			int length;
	
			while ((length = is.read(b)) != -1) {
				os.write(b, 0, length);
			}
	
			is.close();
			os.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
}
